/*
 * All content copyright http://www.j2eefast.com, unless
 * otherwise indicated. All rights reserved.
 * No deletion without permission
 */
package com.clwl.supervise.superviseapp.service.certificaReview;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clwl.supervise.superviseapp.beans.certificaReview.*;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.base.TsDept;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsDeptMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsUserMapper;
import com.clwl.supervise.superviseapp.mapper.certificaReview.*;
import com.clwl.supervise.superviseapp.mapper.supervise.JgCertificaReviewPersonMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgCheckContentMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgClassifySpscMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.JgStandardMapper;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 证后审查Service接口
 *
 * @author: GuXueJian
 * @date 2023-10-13 13:49:07
 */
@Service
public class JgCertificaReviewService extends ServiceImpl<JgCertificaReviewMapper, JgCertificaReview> {

    @Resource
    private JgCertificaReviewMapper jgCertificaReviewMapper;
    @Resource
    private JgCertificaReviewStandardMapper jgCertificaReviewStandardMapper;
    @Resource
    private JgCertificaReviewContentMapper jgCertificaReviewContentMapper;
    @Resource
    private JgCertificaReviewTeamMapper jgCertificaReviewTeamMapper;
    @Resource
    private JgCertificaReviewFileMapper certificaReviewFileMapper;
    @Resource
    private JgCertificaReviewPersonMapper certificaReviewPersonMapper;
    @Resource
    private TsUserMapper tsUserMapper;

    @Resource
    private TsDeptMapper deptMapper;
    @Resource
    TcCompanyMapper tcCompanyMapper;

    @Resource
    JgClassifySpscMapper classifySpscMapper;

    @Resource
    JgStandardMapper jgStandardMapper;
    @Resource
    JgCheckContentMapper jgCheckContentMapper;
    @Resource
    JgExpertArchivesMapper jgExpertArchivesMapper;

    /**
     * 获取证后审查列表
     *
     * @param params
     * @return
     */
    public Map<String, Object> getCertificaReviewVoList(Integer pageNum, Integer pageSize, CertificaReviewSearchParams params) {
        Map<String, Object> resultMap = new HashMap<>();
        if (null == pageNum || null == pageSize) {
            resultMap.put("code", "1");
            resultMap.put("msg", "没有传入分页信息");
            return resultMap;
        }
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
//        String deptType = "3";
//        if ("0".equals(dataRange)) {
//            deptType = "0";
//        } else if ("1".equals(dataRange)) {
//            deptType = "1";
//        } else if ("2".equals(dataRange)) {
//            deptType = "2";
//        } else if ("3".equals(dataRange)) {
//            deptType = "2";
//        }
        if (!UserHelper.getUserId().equals("0") && !dataRange.equals("0")) {
            TsDept dept = deptMapper.selectById(UserHelper.getUserInfo().getDeptId());
            if (dataRange.equals("1")) {
                params.setDeptQuId(dept.getParentId());
            }
            else if (dept.getLvl() == 2 && StringUtils.equals("1", dept.getParentId() + "")) {
                params.setDeptQuId(UserHelper.getUserInfo().getDeptId());
            } else {
                params.setDeptId(UserHelper.getUserInfo().getDeptId());
            }

        }
//        TsDept dataDeptEntity = deptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
//        if (dataDeptEntity != null) {
//            params.setDataDeptId(dataDeptEntity.getId());
//        } else {
//            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
//        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }

        List<String> processList = CompanyProcessUtil.getUserProcessList();
        params.setProcessList(processList);

        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setSearchCount(false);
        iPage.setOptimizeCountSql(false);
        IPage<CertificaReviewVo> page = jgCertificaReviewMapper.findCertificaReviewVoList(iPage, params);

        List<CertificaReviewVo> dataList = page.getRecords();
        if (CollectionUtils.isEmpty(dataList)) {
            dataList = new ArrayList<>();
        }
        resultMap.put("code", "0");
        resultMap.put("msg", "成功");
        resultMap.put("data", dataList);
        return resultMap;
    }

    /**
     * 获取高级查询依赖项
     */
    public List<String> getCheckYearList() {
        List<String> checkYearList = new ArrayList<>();
        String minCheckYear = jgCertificaReviewMapper.getMinCheckYear();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String thisYear = sdf.format(new Date());
        if (StringUtils.isBlank(minCheckYear)) {
            checkYearList.add(thisYear);
            return checkYearList;
        }
        Integer numThisYear = Integer.valueOf(thisYear);
        Integer numMinCheckYear = Integer.valueOf(minCheckYear);
        while (numThisYear >= numMinCheckYear) {
            checkYearList.add(String.valueOf(numThisYear));
            numThisYear--;
        }
        return checkYearList;
    }

    /**
     * 获取证后审查录入页面信息
     */
    public Map<String, Object> getCertificaReviewEnterInfo(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> datatMap = new HashMap<>();
        if (null == id) {
            resultMap.put("code", "1");
            resultMap.put("msg", "证后审查ID为空");
            return resultMap;
        }
        //证后审查主表信息
        JgCertificaReview jgCertificaReview = jgCertificaReviewMapper.selectById(id);
        if (null == jgCertificaReview) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取证后审查信息失败");
            return resultMap;
        }
        if (0 != jgCertificaReview.getReviewStatus()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "已审查信息不能重复录入");
            return resultMap;
        }
        /**
         * 审查信息
         */
        Map<String, Object> reviewInfoMap = new HashMap<>();
        /**
         * 审查类别 groupLeader teamMember
         */

        List<JgClassifySpsc> classifySpscEntityList = classifySpscMapper.selectClassifySpscFirstByCompany(jgCertificaReview.getCompanyId());
        reviewInfoMap.put("reviewCategory", classifySpscEntityList);
        /**
         * 如果审查信息临时保存 加载审查组信息
         */
        if (jgCertificaReview.getStorageType() != null && jgCertificaReview.getStorageType() == 1) {
            List<JgCertificaReviewTeam> teamList = jgCertificaReviewTeamMapper.findByCertificaReviewId(id);
            if (CollectionUtils.isEmpty(teamList)) {
                resultMap.put("code", "1");
                resultMap.put("msg", "获取审查组信息失败");
                return resultMap;
            }
            List<Map<String, Object>> personList = new ArrayList<>();
            for (JgCertificaReviewTeam teamMember : teamList) {
                if (teamMember.getReviewerType() == 0) {
                    reviewInfoMap.put("groupLeader", teamMember.getReviewerName());
                } else {
                    Map<String, Object> user = new HashMap<>();
                    user.put("name", teamMember.getReviewerName());
                    personList.add(user);
                }
            }
            reviewInfoMap.put("personList", personList);
        }


        /**
         * 监管单位信息
         */
        Map<String, Object> aupervisionUnitMap = new HashMap<>();

        aupervisionUnitMap.put("deptName", jgCertificaReview.getDeptName());
        aupervisionUnitMap.put("reviewTime", DateUtil.format(jgCertificaReview.getReviewTime(), "yyyy-MM-dd HH:mm"));
        //生产经营主体信息
        if (null == jgCertificaReview.getCompanyId()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "没有关联经营主体");
            return resultMap;
        }
        TcCompany tcCompany = tcCompanyMapper.selectById(jgCertificaReview.getCompanyId());
        if (null == tcCompany) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取经营主体失败");
            return resultMap;
        }
        String scCode = "spsc,tssc";
        if (scCode.indexOf(tcCompany.getSupProcess()) <= -1) {
            resultMap.put("code", "1");
            resultMap.put("msg", "关联企业主体不是生产环节企业");
            return resultMap;
        }
        /**
         * 经营主体信息
         */
        Map<String, Object> businessEntityMap = new HashMap<>();
        //主体类别
        String businessCategory = tcCompanyMapper.getScbusinessCategory(tcCompany.getId());
        businessEntityMap.put("companyName", tcCompany.getCompanyName());
        businessEntityMap.put("address", tcCompany.getAddress());
        businessEntityMap.put("legalPerson", tcCompany.getLegalPerson());
        businessEntityMap.put("businessCategory", businessCategory);
        businessEntityMap.put("businessScope", tcCompany.getBusinessScope());
        businessEntityMap.put("LICENSE", tcCompany.getLicense());

        /**
         * 审查内容信息
         */
        if (null == jgCertificaReview.getTemplateId()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "该审查没有关联模板信息");
            return resultMap;
        }
        Map<String, Object> templateMap = new HashMap<>();
        templateMap.put("templateName", jgCertificaReview.getTemplateName());
        // List<JgClassifySpsc> jgClassifySpscList = classifySpscMapper.selectClassifySpscFirstByCompany(tcCompany.getId());
        if (jgCertificaReview.getStorageType() != null && 1 == jgCertificaReview.getStorageType()) {
            /**
             * 审查内容信息
             */
            List<JgCertificaReviewStandard> standardList = jgCertificaReviewStandardMapper.findByCertificationReviewId(jgCertificaReview.getId());
            if (CollectionUtils.isEmpty(standardList)) {
                resultMap.put("code", "1");
                resultMap.put("msg", "获取检查标准信息错误");
                return resultMap;
            }
            List<Map<String, Object>> standardMapList = new ArrayList<>();
            for (JgCertificaReviewStandard standard : standardList) {

                List<JgCertificaReviewContent> contentList = jgCertificaReviewContentMapper.findByCertificaReviewStandardId(standard.getId());
                if (CollectionUtils.isEmpty(contentList)) {
                    resultMap.put("code", "1");
                    resultMap.put("msg", "获取检查内容信息错误");
                    return resultMap;
                }
                Map<String, Object> standardMap = new HashMap<>();
                standardMap.put("standardId", standard.getStandardId());
                standardMap.put("serialNum", standard.getSerialNum());
                standardMap.put("standardName", standard.getName());

                standardMap.put("contentList", contentList);
                standardMapList.add(standardMap);
            }
            if (CollectionUtils.isEmpty(standardMapList)) {
                resultMap.put("code", "1");
                resultMap.put("msg", "获取检查标准、内容信息错误");
                return resultMap;
            }
            templateMap.put("standardList", standardMapList);
        } else {
            List<SimpleTemplateStandardVo> standardList = jgStandardMapper.getSimpleTemplateStandard(jgCertificaReview.getTemplateId());
            if (CollectionUtils.isEmpty(standardList)) {
                resultMap.put("code", "1");
                resultMap.put("msg", "获取检查标准信息错误");
                return resultMap;
            }
            int index = 1;
            for (SimpleTemplateStandardVo standard : standardList) {
                standard.setSerialNum(Long.parseLong(index + ""));
                int index2 = 1;
                List<SimpleTemplateContentVo> contentList = jgCheckContentMapper.getSimpleTemplateContent(standard.getStandardId());
                for (SimpleTemplateContentVo simpleTemplateContentVo : contentList) {
                    simpleTemplateContentVo.setSerialNum(Long.parseLong(index2 + ""));
                    index2 = index2 + 1;
                }
                if (CollectionUtils.isEmpty(contentList)) {
                    resultMap.put("code", "1");
                    resultMap.put("msg", "获取检查内容信息错误");
                    return resultMap;
                }
                index = index + 1;
                standard.setContentList(contentList);
            }
            templateMap.put("standardList", standardList);
        }
        if (jgCertificaReview.getStorageType() != null && 1 == jgCertificaReview.getStorageType()) {
            //审查结果信息
            Map<String, Object> reviewConclusionMap = new HashMap<>();
            //审查结果 1：合格 2：基本合格 3：不合格
            reviewConclusionMap.put("reviewResults", jgCertificaReview.getReviewResults());
            //实际扣分数
            reviewConclusionMap.put("actualDeductionPoints", jgCertificaReview.getActualDeductionPoints());
            //有无异议
            reviewConclusionMap.put("corporateObjection", jgCertificaReview.getCorporateObjection());
            //异议说明
            reviewConclusionMap.put("objectionStatement", jgCertificaReview.getObjectionStatement());

            datatMap.put("reviewConclusion", reviewConclusionMap);
        }
        if (jgCertificaReview.getStorageType() != null && 1 == jgCertificaReview.getStorageType()) {
            datatMap.put("storageType", jgCertificaReview.getStorageType());
        } else {
            datatMap.put("storageType", 0);
        }

        datatMap.put("reviewInfo", reviewInfoMap);
        datatMap.put("aupervisionUnit", aupervisionUnitMap);
        //经营主体信息
        datatMap.put("businessEntity", businessEntityMap);
        //检查标准内容信息
        datatMap.put("templateInfo", templateMap);

        resultMap.put("code", "0");
        resultMap.put("msg", "成功");
        resultMap.put("data", datatMap);
        return resultMap;
    }
/**
 * 获取审查组专家信息（没有表）
 */
    /**
     * 获取监管人员列表信息
     */
    public Map<String, Object> getSupervisors(Integer pageNum, Integer pageSize, Long companyId, String name, String userRole) {
        Map<String, Object> resultMap = new HashMap<>();
        Page<JgCertificaReviewPerson> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        QueryWrapper<JgCertificaReviewPerson> queryWrapper = new QueryWrapper();
        queryWrapper.eq("DELETE_FLAG", 0);
        queryWrapper.eq("USER_TYPE", 1);
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("USER_NAME", "%" + name + "%");
        }
        if (StringUtils.isNotBlank(userRole)) {
            if (StringUtils.equals(userRole, "0")) {
                //只查询企业所在部门下的科长或所长,去除审查专家
                TcCompany company = tcCompanyMapper.selectById(companyId);
                queryWrapper.in("DEPT_QU_ID", company.getDeptQuId());
                queryWrapper.in("POSITION_CODE", 11, 8);
            }
        }
        queryWrapper.orderByDesc("ID");
        IPage<JgCertificaReviewPerson> page = certificaReviewPersonMapper.selectPage(iPage, queryWrapper);

        List<JgCertificaReviewPerson> userList = page.getRecords();
        List<SupervisorVo> supervisorList = new ArrayList<>();
        for (JgCertificaReviewPerson user : userList) {
            SupervisorVo supervisorVo = new SupervisorVo();
            supervisorVo.setId(user.getId());
            supervisorVo.setName(user.getUserName());
            supervisorVo.setMobile(user.getTelephone());
            supervisorVo.setEnforcementNo(user.getEnforcementNo());
            supervisorVo.setPositionName(user.getPositionName());
            supervisorVo.setUserType(user.getUserType());//人员类型1-监管人员；2-审查专家

            if (user.getDeptId() != null) {
                TsDept dept = deptMapper.selectById(user.getDeptId());
                supervisorVo.setAffiliatedUnitName(dept.getName());
                if (null == dept.getParentId() || 1 == dept.getParentId()) {
                    supervisorVo.setDistrictBureauName(dept.getName());
                } else {
                    TsDept districtBureau = getBureauLevelDept(dept.getParentId());
                    if (null == districtBureau) {
                        supervisorVo.setDistrictBureauName("");
                    } else {
                        supervisorVo.setDistrictBureauName(districtBureau.getName());
                    }
                }
            }
            supervisorList.add(supervisorVo);
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("pageNum", page.getCurrent());
        dataMap.put("pageSize", page.getSize());
        dataMap.put("total", page.getTotal());
        dataMap.put("pages", page.getPages());
        dataMap.put("dataList", supervisorList);
        resultMap.put("code", "0");
        resultMap.put("msg", "成功");
        resultMap.put("data", dataMap);
        return resultMap;
    }

    /**
     * 获取专家档案
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    public Map<String, Object> getExpertArchives(Integer pageNum, Integer pageSize, Long companyId, String name) {
        Map<String, Object> resultMap = new HashMap<>();
//        TcCompany company = tcCompanyMapper.selectById(companyId);
        Page<JgCertificaReviewPerson> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        QueryWrapper<JgCertificaReviewPerson> queryWrapper = new QueryWrapper();
        queryWrapper.eq("DELETE_FLAG", 0);
        queryWrapper.eq("USER_TYPE", 2);
        //queryWrapper.eq("DEPT_ID",company.getDeptId());
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("USER_NAME", "%" + name + "%");
        }
        IPage<JgCertificaReviewPerson> page = certificaReviewPersonMapper.selectPage(iPage, queryWrapper);

        List<JgCertificaReviewPerson> userList = page.getRecords();

        List<SupervisorVo> supervisorList = new ArrayList<>();
        for (JgCertificaReviewPerson user : userList) {
            SupervisorVo supervisorVo = new SupervisorVo();
            supervisorVo.setId(user.getId());
            supervisorVo.setName(user.getUserName());
            supervisorVo.setAffiliatedUnitName(user.getWorkUnit());
            supervisorVo.setMobile(user.getTelephone());
            supervisorVo.setEnforcementNo(user.getEnforcementNo());
            supervisorVo.setPositionName(user.getJob());

            if (user.getDeptId() != null) {
                TsDept dept = deptMapper.selectById(user.getDeptId());
                supervisorVo.setAffiliatedUnitName(dept.getName());
                if (null == dept.getParentId() || 1 == dept.getParentId()) {
                    supervisorVo.setDistrictBureauName(dept.getName());
                } else {
                    TsDept districtBureau = getBureauLevelDept(dept.getParentId());
                    if (null == districtBureau) {
                        supervisorVo.setDistrictBureauName("");
                    } else {
                        supervisorVo.setDistrictBureauName(districtBureau.getName());
                    }
                }
            }
            supervisorList.add(supervisorVo);
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("pageNum", page.getCurrent());
        dataMap.put("pageSize", page.getSize());
        dataMap.put("total", page.getTotal());
        dataMap.put("pages", page.getPages());
        dataMap.put("dataList", supervisorList);
        resultMap.put("code", "0");
        resultMap.put("msg", "成功");
        resultMap.put("data", dataMap);
        return resultMap;
    }

    /**
     * 通过递归方式获取局级管理部门
     *
     * @param parentId
     * @return
     */
    public TsDept getBureauLevelDept(Long parentId) {
        if (null != parentId) {
            TsDept bureauLevelDept = deptMapper.selectById(parentId);
            if (null != bureauLevelDept) {
                if (null != bureauLevelDept.getParentId()) {
                    if (bureauLevelDept.getParentId() == 1) {
                        return bureauLevelDept;
                    } else {
                        bureauLevelDept = getBureauLevelDept(bureauLevelDept.getParentId());
                    }
                }
            }
        }

        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    /**
     * 保存证后审查信息（1临时保存 2 永久保存）
     */
    public Map<String, Object> saveReviewEnterInfo(String json) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(json)) {
            resultMap.put("code", "1");
            resultMap.put("msg", "没有传参！");
            return resultMap;
        }
        if (!JSONUtil.isJson(json)) {
            resultMap.put("code", "1");
            resultMap.put("msg", "传入数据为非JSON格式");
            return resultMap;
        }
        JSONObject requestObj = JSONObject.parseObject(json);
        if (null == requestObj) {
            resultMap.put("code", "1");
            resultMap.put("msg", "JSON转换失败");
            return resultMap;
        }
        if (!requestObj.containsKey("id")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入id字段信息");
            return resultMap;
        }
        if (!requestObj.containsKey("saveType")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入saveType字段信息");
            return resultMap;
        }
        if (!requestObj.containsKey("reviewResults")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入reviewResults字段信息");
            return resultMap;
        }
        if (!requestObj.containsKey("actualDeductionPoints")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入saveType字段信息");
            return resultMap;
        }
        if (!requestObj.containsKey("corporateObjection")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入corporateObjection字段信息");
            return resultMap;
        }
        if (!requestObj.containsKey("reviewTeam")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入reviewTeam字段信息");
            return resultMap;
        }
        if (!requestObj.containsKey("reviewContent")) {
            resultMap.put("code", "1");
            resultMap.put("msg", "参数中没有传入id字段信息");
            return resultMap;
        }
        //校验结束 准备开始保存
        JgCertificaReview jgCertificaReview = jgCertificaReviewMapper.selectById(requestObj.getLong("id"));
        if (null == jgCertificaReview) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取对应证后审查任务信息错误");
            return resultMap;
        }
  /*      Integer storageType = jgCertificaReview.getStorageType();
        jgCertificaReview.setReviewTime(new Date());*/
        jgCertificaReview.setReviewResults(requestObj.getInteger("reviewResults"));
        jgCertificaReview.setActualDeductionPoints(requestObj.getInteger("actualDeductionPoints"));
        jgCertificaReview.setCorporateObjection(requestObj.getInteger("corporateObjection"));
        if (1 == requestObj.getInteger("corporateObjection")) {
            if (StringUtils.isBlank(requestObj.getString("objectionStatement"))) {
                resultMap.put("code", "1");
                resultMap.put("msg", "企业有异议实，异议内容不能为空");
                return resultMap;
            }
            jgCertificaReview.setObjectionStatement(requestObj.getString("objectionStatement"));
        }
        //如果是永久保存 设置审查状态为已审查
        if (2 == requestObj.getInteger("saveType")) {
            jgCertificaReview.setReviewStatus(1);
            jgCertificaReview.setStorageType(2);
        } else {
            jgCertificaReview.setStorageType(1);
        }
        JSONArray reviewTeamArray = requestObj.getJSONArray("reviewTeam");
        JSONArray reviewContentArray = requestObj.getJSONArray("reviewContent");
        if (null == reviewTeamArray || reviewTeamArray.isEmpty()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取审查组参数信息失败");
            return resultMap;
        }
        if (null == reviewContentArray || reviewContentArray.isEmpty()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取检查内容信息参数失败");
            return resultMap;
        }
        //如果已经临时保存则对审查组信息 检查内容进行更新 reviewContent
        /*   if (storageType != null && 1 == storageType) {
         *//**
         * 更新审查组信息
         *//*
            List<JgCertificaReviewTeam> teamList = jgCertificaReviewTeamMapper.findByCertificaReviewId(jgCertificaReview.getId());
            if (CollectionUtils.isEmpty(teamList)) {
                resultMap.put("code", "1");
                resultMap.put("msg", "获取审查组信息失败");
                return resultMap;
            }
            boolean haveLevel0 = false;
            List<JgCertificaReviewTeam> updateList = new ArrayList<>();
            for (int i = 0; i < reviewTeamArray.size(); i++) {
                JSONObject teamObj = reviewTeamArray.getJSONObject(i);
                Long id = teamObj.getLong("id");
                Integer level = teamObj.getInteger("level");
                Integer identity = teamObj.getInteger("identity");
                String userName = "";
                if (0 == identity) {
                    JgCertificaReviewPerson user = certificaReviewPersonMapper.selectById(id);
                    if (user == null) {
                        resultMap.put("code", "1");
                        resultMap.put("msg", "获取ID为：" + id + "监管人员信息失败");
                        return resultMap;
                    }
                    userName = user.getUserName();
                } else {
                    //获取审查人员信息
                    userName = "审查";
                }
                JgCertificaReviewTeam reviewTeam = null;
                for (JgCertificaReviewTeam team : teamList) {
                    if (team.getSortLevel() == level) {
                        reviewTeam = team;
                        teamList.remove(team);
                    }
                }
                if (null == reviewTeam) {
                    reviewTeam = new JgCertificaReviewTeam();
                    reviewTeam.setCertificationReviewId(jgCertificaReview.getId());
                    if (level == 0) {
                        reviewTeam.setReviewerType(0);
                        if (haveLevel0) {
                            resultMap.put("code", "1");
                            resultMap.put("msg", "组长只能指定一人");
                            return resultMap;
                        }
                        haveLevel0 = true;
                    } else {
                        reviewTeam.setReviewerType(1);
                    }
                    reviewTeam.setSortLevel(level);
                    reviewTeam.setReviewerName(userName);
                    reviewTeam.setBirthId(id);
                    reviewTeam.setBirth(identity);
                    updateList.add(reviewTeam);
                } else {
                    if (level == 0) {
                        reviewTeam.setReviewerType(0);
                        if (haveLevel0) {
                            resultMap.put("code", "1");
                            resultMap.put("msg", "组长只能指定一人");
                            return resultMap;
                        }
                        haveLevel0 = true;
                    } else {
                        reviewTeam.setReviewerType(1);
                    }
                    reviewTeam.setSortLevel(level);
                    reviewTeam.setReviewerName(userName);
                    reviewTeam.setBirthId(id);
                    reviewTeam.setBirth(identity);
                    updateList.add(reviewTeam);
                }
            }
            //如果没有指定组长
            if (!haveLevel0) {
                resultMap.put("code", "1");
                resultMap.put("msg", "没有指定组长");
                return resultMap;
            }
            List<JgCertificaReviewContent> updateContentList = new ArrayList<>();
            for (int x = 0; x < reviewContentArray.size(); x++) {
                JSONObject contentObj = reviewContentArray.getJSONObject(0);
                Long standardId = contentObj.getLong("standardId");
                Long contentId = contentObj.getLong("contentId");
                Integer selected = contentObj.getInteger("selected");
                String problemContent = contentObj.getString("problemContent");
                String reviewCategory = contentObj.getString("reviewCategory");
                *//**
         * 获取证后审查标准信息
         *//*
                QueryWrapper<JgCertificaReviewStandard> standardWrapper = new QueryWrapper();
                standardWrapper.eq("STANDARD_ID", standardId);
                standardWrapper.eq("CERTIFICATION_REVIEW_ID", jgCertificaReview.getId());
                JgCertificaReviewStandard jgCertificaReviewStandard = jgCertificaReviewStandardMapper.selectOne(standardWrapper);

                QueryWrapper<JgCertificaReviewContent> queryWrapper = new QueryWrapper();
                queryWrapper.eq("CONTENT_ID", contentId);
                queryWrapper.eq("CERTIFICA_REVIEW_STANDARD_ID", jgCertificaReviewStandard.getId());
                JgCertificaReviewContent jgCertificaReviewContent = jgCertificaReviewContentMapper.selectOne(queryWrapper);
                jgCertificaReviewContent.setSelection(selected);
                jgCertificaReviewContent.setProblemContent(StringUtils.equals(problemContent,"undefined") ? "":problemContent);
                jgCertificaReviewContent.setReviewCategory(StringUtils.equals(reviewCategory,"undefined") ? "":reviewCategory);
                if (2 == selected) {
                    String problemImgPath = contentObj.getString("problemImgPath");
                    jgCertificaReviewContent.setProblemFile(problemImgPath);
                }
                updateContentList.add(jgCertificaReviewContent);
            }
            if (!CollectionUtils.isEmpty(teamList)) {
                List<Long> idList = new ArrayList<>();
                for (JgCertificaReviewTeam team : teamList) {
                    idList.add(team.getId());
                }
                jgCertificaReviewTeamMapper.deleteBatchIds(idList);
            }
            if (!CollectionUtils.isEmpty(updateList)) {
                for (JgCertificaReviewTeam te : updateList) {
                    if (null == te.getId()) {
                        jgCertificaReviewTeamMapper.insert(te);
                    } else {
                        jgCertificaReviewTeamMapper.updateById(te);
                    }
                }

            }
            if (!CollectionUtils.isEmpty(updateContentList)) {
                for (JgCertificaReviewContent tc : updateContentList) {
                    if (null == tc.getId()) {
                        jgCertificaReviewContentMapper.insert(tc);
                    } else {
                        jgCertificaReviewContentMapper.updateById(tc);
                    }
                }

            }
            jgCertificaReviewMapper.updateById(jgCertificaReview);
            resultMap.put("code", "0");
            resultMap.put("msg", "成功");
            return resultMap;
        } else {*/
        //如果没有临时保存 则进行保存
        boolean haveLevel0 = false;
        List<JgCertificaReviewTeam> updateList = new ArrayList<>();
        for (int i = 0; i < reviewTeamArray.size(); i++) {
            JSONObject teamObj = reviewTeamArray.getJSONObject(i);
            Long id = teamObj.getLong("id");
            Integer level = teamObj.getInteger("level");
            Integer identity = teamObj.getInteger("identity");
            String userName = "";
            if (id == null) {
                //没选人的话就不保存
                continue;
            }
            if (0 == identity) {
                JgCertificaReviewPerson user = certificaReviewPersonMapper.selectById(id);
                if (user == null) {
                    resultMap.put("code", "1");
                    resultMap.put("msg", "获取ID为：" + id + "监管人员信息失败");
                    return resultMap;
                }
                userName = user.getUserName();
            } else {
                //获取审查人员信息
                userName = "审查";
            }

            JgCertificaReviewTeam reviewTeam = new JgCertificaReviewTeam();
            reviewTeam.setCertificationReviewId(jgCertificaReview.getId());
            if (level == 0) {
                reviewTeam.setReviewerType(0);
                if (haveLevel0) {
                    resultMap.put("code", "1");
                    resultMap.put("msg", "组长只能指定一人");
                    return resultMap;
                }
                haveLevel0 = true;
            } else {
                reviewTeam.setReviewerType(1);
            }
            reviewTeam.setSortLevel(level);
            reviewTeam.setReviewerName(userName);
            reviewTeam.setBirthId(id);
            reviewTeam.setBirth(identity);
            updateList.add(reviewTeam);

        }
        //如果没有指定组长
        if (!haveLevel0) {
            resultMap.put("code", "1");
            resultMap.put("msg", "没有指定组长");
            return resultMap;
        }
        /**
         * 审查内容信息
         */
        if (null == jgCertificaReview.getTemplateId()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "该审查没有关联模板信息");
            return resultMap;
        }
        List<JgStandard> standardList = jgStandardMapper.getStanardByTemplateId(jgCertificaReview.getTemplateId());
        if (CollectionUtils.isEmpty(standardList)) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取检查标准信息错误");
            return resultMap;
        }

        for (JgStandard standard : standardList) {
            int index = 1;
            List<JgCheckContent> contentList = jgCheckContentMapper.selectEntityByStandardId(standard.getId());
            if (CollectionUtils.isEmpty(contentList)) {
                resultMap.put("code", "1");
                resultMap.put("msg", "获取检查内容信息错误");
                return resultMap;
            }
            JgCertificaReviewStandard jcStandard = new JgCertificaReviewStandard();
            jcStandard.setCertificationReviewId(jgCertificaReview.getId());
            jcStandard.setTemplateId(jgCertificaReview.getTemplateId());
            jcStandard.setStandardId(standard.getId());
            jcStandard.setSupCategory("2");
            jcStandard.setSupProcess(standard.getSupProcess());
            jcStandard.setSpxsId(standard.getSpxsId());
            jcStandard.setCyfwId(standard.getCyfwId());
            jcStandard.setSpscLbId(standard.getSpscLbId());
            jcStandard.setSpscLbZlId(standard.getSpscLbZlId());
            jcStandard.setTsspLbId(standard.getTsspLbId());
            jcStandard.setTsspLbZlId(standard.getTsspLbZlId());
            jcStandard.setName(standard.getName());
            jcStandard.setSerialNum(Double.parseDouble(index + ""));
            jcStandard.setCreatorId(standard.getCreatorId());
            jcStandard.setCreator(standard.getCreator());
            jcStandard.setDeleteFlag(0);
            jgCertificaReviewStandardMapper.insert(jcStandard);
            index = index + 1;
            int index2 = 1;
            for (JgCheckContent content : contentList) {
                int selection = 0;
                Long standardId = null;
                Long contentId = null;
                Integer selected = null;
                String reviewCategory = "";
                String problemContent = "";
                String problemImgPath = "";
                for (int x = 0; x < reviewContentArray.size(); x++) {
                    JSONObject contentObj = reviewContentArray.getJSONObject(x);
                    if (StringUtils.equals(content.getId() + "", contentObj.getString("contentId"))) {
                        selected = contentObj.getInteger("selected");
                        problemContent = contentObj.getString("problemContent");
                        reviewCategory = contentObj.getString("reviewCategory");
                        problemImgPath = contentObj.getString("problemImgPath");
                        break;
                    }
                }
                JgCertificaReviewContent jgCertificaReviewContent = new JgCertificaReviewContent();
                jgCertificaReviewContent.setContentId(content.getId());
                jgCertificaReviewContent.setCertificaReviewStandardId(jcStandard.getId());
                jgCertificaReviewContent.setCheckContent(content.getCheckContent());
                jgCertificaReviewContent.setImportentItem(content.getImportentItem());
                jgCertificaReviewContent.setMissingItem(content.getMissingItem());
                jgCertificaReviewContent.setReviewCategory(StringUtils.equals(reviewCategory, "undefined") ? "" : reviewCategory);
                jgCertificaReviewContent.setSerialNum(Double.parseDouble(index2 + ""));
                if (selected == null) {
                    continue;
                }
                if (1 == selected) {
                    jgCertificaReviewContent.setScore(content.getYesScore());
                } else {
                    jgCertificaReviewContent.setScore(content.getScore());
                }

                jgCertificaReviewContent.setSelection(selected);
                jgCertificaReviewContent.setProblemContent(problemContent);
                if (2 == selected) {
                    jgCertificaReviewContent.setProblemFile(problemImgPath);
                }
                if (3 == selected) {
                    jgCertificaReviewContent.setMissingItemContent(problemContent);
                }
                jgCertificaReviewContent.setDeleteFlag(0);
                jgCertificaReviewContent.setCreatorId(content.getCreatorId());
                jgCertificaReviewContent.setCreator(content.getCreator());
                jgCertificaReviewContentMapper.insert(jgCertificaReviewContent);
                index2 = index2 + 1;
            }
        }
/**
 * 保存审查组信息
 */
        if (!CollectionUtils.isEmpty(updateList)) {
            for (JgCertificaReviewTeam te : updateList) {
                if (null == te.getId()) {
                    jgCertificaReviewTeamMapper.insert(te);
                } else {
                    jgCertificaReviewTeamMapper.updateById(te);
                }
            }

        }
        jgCertificaReviewMapper.updateById(jgCertificaReview);
        resultMap.put("code", "0");
        resultMap.put("msg", "成功");
        return resultMap;
        //}
    }

    /**
     * 获取证后审查明细信息
     */
    public Map<String, Object> getCertificaReviewDtl(Long id) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> datatMap = new HashMap<>();
        if (null == id) {
            resultMap.put("code", "1");
            resultMap.put("msg", "证后审查ID为空");
            return resultMap;
        }
        //证后审查主表信息
        JgCertificaReview jgCertificaReview = jgCertificaReviewMapper.selectById(id);
        if (null == jgCertificaReview) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取证后审查信息失败");
            return resultMap;
        }
        if (1 != jgCertificaReview.getReviewStatus()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "未审查信息请先进行审查操作");
            return resultMap;
        }
        List<JgCertificaReviewTeam> teamList = jgCertificaReviewTeamMapper.findByCertificaReviewId(id);
        if (CollectionUtils.isEmpty(teamList)) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取审查组信息失败");
            return resultMap;
        }
        /**
         * 审查信息
         */
        Map<String, Object> reviewInfoMap = new HashMap<>();
        /**
         * 审查类别 groupLeader teamMember
         */
        reviewInfoMap.put("reviewCategory", jgCertificaReview.getReviewCategory());

        List<Map<String, Object>> personList = new ArrayList<>();
        for (JgCertificaReviewTeam teamMember : teamList) {
            if (teamMember.getReviewerType() == 0) {
                reviewInfoMap.put("groupLeader", teamMember.getReviewerName());
            } else {
                Map<String, Object> user = new HashMap<>();
                user.put("name", teamMember.getReviewerName());
                personList.add(user);
            }
        }
        reviewInfoMap.put("personList", personList);
        /**
         * 监管单位信息
         */
        Map<String, Object> aupervisionUnitMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd");

        aupervisionUnitMap.put("deptName", jgCertificaReview.getDeptName());
        aupervisionUnitMap.put("reviewTime", jgCertificaReview.getReviewTime() == null ? "" : sdf.format(jgCertificaReview.getReviewTime()));
        //生产经营主体信息
        if (null == jgCertificaReview.getCompanyId()) {
            resultMap.put("code", "1");
            resultMap.put("msg", "没有关联经营主体");
            return resultMap;
        }
        TcCompany tcCompany = tcCompanyMapper.selectById(jgCertificaReview.getCompanyId());
        if (null == tcCompany) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取经营主体失败");
            return resultMap;
        }
        String scCode = "spsc,tssc";
        if (scCode.indexOf(tcCompany.getSupProcess()) <= -1) {
            resultMap.put("code", "1");
            resultMap.put("msg", "关联企业主体不是生产环节企业");
            return resultMap;
        }
        /**
         * 经营主体信息
         */
        Map<String, Object> businessEntityMap = new HashMap<>();
        //主体类别
        String businessCategory = tcCompanyMapper.getScbusinessCategory(tcCompany.getId());
        businessEntityMap.put("companyName", tcCompany.getCompanyName());
        businessEntityMap.put("address", tcCompany.getAddress());
        businessEntityMap.put("legalPerson", null == tcCompany.getLegalPerson() ? "" : tcCompany.getLegalPerson());
        businessEntityMap.put("businessCategory", null == businessCategory ? "" : businessCategory);
        businessEntityMap.put("businessScope", null == tcCompany.getBusinessScope() ? "" : tcCompany.getBusinessScope());
        businessEntityMap.put("LICENSE", tcCompany.getLicense());

        //审查结果信息
        Map<String, Object> reviewConclusionMap = new HashMap<>();
        //审查结果 1：合格 2：基本合格 3：不合格
        reviewConclusionMap.put("reviewResults", jgCertificaReview.getReviewResults());
        //实际扣分数
        reviewConclusionMap.put("actualDeductionPoints", jgCertificaReview.getActualDeductionPoints());
        //有无异议
        reviewConclusionMap.put("corporateObjection", jgCertificaReview.getCorporateObjection());
        //异议说明
        reviewConclusionMap.put("objectionStatement", jgCertificaReview.getObjectionStatement());
        /**
         * 审查内容信息
         */
        List<JgCertificaReviewStandard> standardList = jgCertificaReviewStandardMapper.findByCertificationReviewId(jgCertificaReview.getId());
        if (CollectionUtils.isEmpty(standardList)) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取检查标准信息错误");
            return resultMap;
        }

        List<JgClassifySpsc> classifySpscEntityList = classifySpscMapper.selectClassifySpscFirstByCompany(jgCertificaReview.getCompanyId());
        List<Map<String, Object>> standardMapList = new ArrayList<>();
        for (JgCertificaReviewStandard standard : standardList) {

            List<JgCertificaReviewContent> contentList = jgCertificaReviewContentMapper.findByCertificaReviewStandardId(standard.getId());
            for (JgCertificaReviewContent content : contentList) {
                if (StringUtils.isNotBlank(content.getReviewCategory())) {
                    String classifys = "";
                    String[] cateforyArray = content.getReviewCategory().split(",");
                    List<String> cateforyList = Arrays.asList(cateforyArray);
                    //对比cateforyArray中和classifySpscEntityList中的id对应的name值；
                    for (JgClassifySpsc jgClassifySpsc : classifySpscEntityList) {
                        if (cateforyList.contains(jgClassifySpsc.getId() + "")) {
                            classifys = classifys + jgClassifySpsc.getName() + ",";
                        }
                    }
                    content.setReviewCategory(classifys.substring(0, classifys.length() - 1));
                }
            }
            Map<String, Object> standardMap = new HashMap<>();
            standardMap.put("serialNum", standard.getSerialNum());
            standardMap.put("standardName", standard.getName());
            standardMap.put("contentList", contentList);
            standardMapList.add(standardMap);
        }
        if (CollectionUtils.isEmpty(standardMapList)) {
            resultMap.put("code", "1");
            resultMap.put("msg", "获取检查标准、内容信息错误");
            return resultMap;
        }
        datatMap.put("templateName", jgCertificaReview.getTemplateName());
        datatMap.put("reviewInfo", reviewInfoMap);
        datatMap.put("aupervisionUnit", aupervisionUnitMap);
        //经营主体信息
        datatMap.put("businessEntity", businessEntityMap);
        //审查结果信息
        datatMap.put("reviewConclusion", reviewConclusionMap);
        //检查标准内容信息
        datatMap.put("standardList", standardMapList);
        //文件
        QueryWrapper<JgCertificaReviewFile> certificaReviewFileEntityQueryWrapper = new QueryWrapper<>();
        certificaReviewFileEntityQueryWrapper.eq("certification_review_id", id);
        List<JgCertificaReviewFile> certificaReviewFileList = certificaReviewFileMapper.selectList(certificaReviewFileEntityQueryWrapper);
        datatMap.put("certificaReviewFileList", certificaReviewFileList);

        resultMap.put("code", "0");
        resultMap.put("msg", "成功");
        resultMap.put("data", datatMap);
        return resultMap;
    }
}
